//
//  ViewController.m
//  TotalDemo
//
//  Created by gujian on 16/2/14.
//  Copyright © 2016年 gujian. All rights reserved.
//

#import "ViewController.h"
#import "ListenView.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <dlfcn.h>
#import "IPAddress.h"

#define CELLIDENTIFIER  @"UITableViewCell"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSArray *dataArr;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"主页";
    [self initData];
    [self setupSubViews];
    [self formateDemical];
    [self seperateNumberWithCharset];
    
    [self getWifiList];
    
    [self isPNGORJPEG:[UIImage imageNamed:@"cat.jpg"]];
    [self isPNGORJPEG:[UIImage imageNamed:@"sun"]];

    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"HOST" style:UIBarButtonItemStylePlain target:self action:@selector(getAddress)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
}

- (void)getAddress
{
    //ios.cp.360.cn
    [IPAddress getHostByName:@"dns-oarc.net"];
}

- (void)setupSubViews
{
    UITableView *pTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [pTableView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
    pTableView.dataSource = self;
    pTableView.delegate = self;
    [pTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:CELLIDENTIFIER];
    //相当于内容视图的原点在哪里，即相对于scrollView的origin在哪里，上负下正
    [pTableView setContentInset:UIEdgeInsetsMake(150, 0, 0, 0)];
    [self.view addSubview:pTableView];
    self.tableView = pTableView;
    
    [self.tableView addSubview:[[ListenView alloc] init]];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //相当于scrollView视图滑动了多远的距离,内容视图的原点不变,与scrollView的原点重合
//    [self.tableView setContentOffset:CGPointMake(100, 100)];
}


- (void)initData
{
    _dataArr = @[@{@"图像处理":@"TDHandleImageViewController"},
                 @{@"倒计时器":@"CountDownViewController"},
                 @{@"身份证号":@"IdentityViewController"},
                 @{@"字体间距&行间距":@"TextSpacingViewController"},
                 @{@"数据可视化":@"DataAnalyzingViewController"},
                 @{@"动画":@"AnimationViewController"},
                 @{@"3D动画基础":@"Basic3DAnimationViewController"},
                 @{@"输入长度限制":@"LimitTextFieldViewController"},
                 @{@"UITableView重用机制":@"TDTableViewController"},
                 @{@"AlertViewController":@"AlertViewController"},
                 @{@"旋转木马":@"CarouselViewController"},
                 @{@"TextView":@"GQJTextViewController"},
                 @{@"ContentMode":@"ContentModeViewController"},
                 @{@"发送短信":@"MessageViewController"},
                 @{@"自定义ModalViewController":@"TDViewController"},
                 @{@"图像处理":@"TDImageViewController"},
                 @{@"Block测试":@"GQJBlockViewController"},
                 @{@"weak测试":@"GQJPropertyTestController"},
                 @{@"metaClass测试":@"GQJMetaclassController"},
                 @{@"过度释放问题":@"GQJOverReleasingController"},
                 @{@"KVC&Runtime改变私有变量":@"GQJKVOController"},
                 @{@"OC锁机制":@"GQJLockController"},
                 @{@"拷贝初探":@"GQJCopyController"},
                 @{@"Weak属性初探":@"GQJWeakController"},
                 @{@"自动释放池":@"GQJAutoreleaseController"},
                 @{@"RunLoop":@"GQJRunLoopController"},
                 @{@"LayoutSubview":@"GQJLaySubViewController"},
                 @{@"SwiftController":@"SwiftViewController"},
                 @{@"GQJEqualViewController":@"GQJEqualViewController"},
                 @{@"GQJAutoreleaseObjectController":@"GQJAutoreleaseObjectController"},
                 @{@"GQJIniViewController160818":@"GQJIniViewController160818"},
                 @{@"GQJSingletonController160819":@"GQJSingletonController160819"},
                 @{@"Notification初探":@"GQJNotificationViewController160822"},
                 @{@"探索Category中方法的调用顺序":@"GQJCategoryViewController"},
                 @{@"boundsh和frame":@"GQJBoundsFrameViewController"}
                 ];
}

- (void)formateDemical
{
    //变量控制输出小数点后几位
    LotLog(@"%.*lf", 2,1.203);
}

- (void)getWifiList
{
    CFArrayRef tempArr = CNCopySupportedInterfaces();
    
    if (tempArr != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(tempArr, 0));
        
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary *)CFBridgingRelease(myDict);
            LotLog(@"dict:%@",dict);
        }
    }
    
    LotLog("progress:%d", getSignalStrength());

}

//私有api 获取信号强度
int getSignalStrength()
{
    void *libHandle = dlopen("/System/Library/Frameworks/CoreTelephony.framework/CoreTelephony", RTLD_LAZY);
    int (*CTGetSignalStrength)();
    CTGetSignalStrength = dlsym(libHandle, "CTGetSignalStrength");
    if( CTGetSignalStrength == NULL) LotLog(@"Could not find CTGetSignalStrength");
    int result = CTGetSignalStrength();
    dlclose(libHandle);
    return result;
}

/**
 *  分割字符串
 */
- (void)seperateNumberWithCharset
{
    NSCharacterSet *charSet = [NSCharacterSet whitespaceCharacterSet];
    NSString *originStr = @"One Two Three";
    NSArray *arr = [originStr componentsSeparatedByCharactersInSet:charSet];
    for (id str in arr) {
        if ([str isKindOfClass:[NSString class]]) {
            LotLog(@"%@\n",str);
        }
    }
    NSString *modifiedStr = [arr componentsJoinedByString:@""];
    LotLog(@"originStr:%@\nmodifiedStr:%@",originStr,modifiedStr);
}

/**
 *  判断图片类型
 */
- (void)isPNGORJPEG:(UIImage *)targetImg
{
    NSData *data;
    
    if (UIImagePNGRepresentation(targetImg)) {
        data = UIImagePNGRepresentation(targetImg);
        LotLog(@"png");
    }else
    {
        data = UIImageJPEGRepresentation(targetImg, 1.0);
        LotLog(@"jpeg");
    }
    
    const unsigned char * bytes = [data bytes];
    
    for (int i = 0; i < 4; i++) {
        LotLog(@"byte[%d]:%0x",i,bytes[i]);
    }
}

/**
 * SDWebImageView 中判断image类型
 */

- (NSString *)contentTypeForImageData:(NSData *)data
{
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"image/jpeg";
        case 0x89:
            return @"image/png";
        case 0x47:
            return @"image/git";
        case 0x49:
        case 0x4D:
            return @"image/tiff";
         case 0x52:
            // R as RIFF for WEBP
            if ([data length] < 12) {
                return nil;
            }
            
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"image/webp";
            }
            return nil;
        
    }
    
    return nil;
}


#pragma mark - UITableView datasource delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return _dataArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELLIDENTIFIER forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = [[_dataArr objectAtIndex:indexPath.row] allKeys][0];
    
    return cell;
}

#pragma mark - UITableView delegate

//- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
//{
//    return CGFLOAT_MIN;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
//    if (section > _dataArr.count-1) {
//        return CGFLOAT_MIN;
//    }
//    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *classStr = [[_dataArr objectAtIndex:indexPath.row] allValues][0];
    Class controller = NSClassFromString(classStr);
    if (controller == nil) {
        
        NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
        NSString *classNameFromSwift = [NSString stringWithFormat:@"_TtC%lu%@%lu%@",(unsigned long)appName.length,appName,(unsigned long)classStr.length,classStr];
        controller = NSClassFromString(classNameFromSwift);
        
        
    }
    UIViewController *pushedController = [controller new];
    [self.navigationController pushViewController:pushedController animated:YES];
    
}


#pragma mark - UIScrollView delegate

- (void)checkVisiblilityOfCell:(UITableViewCell *)cell inScrollView:(UIScrollView *)scrollView
{
    CGRect rect = [scrollView convertRect:cell.frame toView:scrollView.superview];
    
    if (CGRectContainsRect(scrollView.frame, rect)) {
        //完全显示
    }else
    {
        //部分显示
        [self notiUnCompleteVisibleWithCell:cell scrollView:scrollView];
    }
    
    
    
}

- (void)notiUnCompleteVisibleWithCell:(UITableViewCell *)cell scrollView:(UIScrollView *)scrollView
{
    CGRect rect = [scrollView convertRect:cell.frame toView:scrollView.superview];
    CGFloat cellOffY = rect.origin.y;
    
    CGFloat cellHeight = rect.size.height;
    CGFloat alpha = 1 + cellOffY/cellHeight;
    if (cellOffY > 0) {
        alpha = (scrollView.frame.size.height - cellOffY)/cellHeight;
    }
    
    if (alpha > 1) {
        alpha = 1.0f;
    }else if (alpha < 0)
        alpha = 0.0f;

    cell.alpha = alpha;
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *visibleCells = self.tableView.visibleCells;
    NSUInteger cellCount = visibleCells.count;
    
    if (cellCount == 0) {
        return;
    }
    
    //check the visibility of the first cell
    [self checkVisiblilityOfCell:[visibleCells firstObject] inScrollView:scrollView];
    
    if (cellCount == 1) {
        return;
    }
    
//    check the visibility of the last cell
    [self checkVisiblilityOfCell:[visibleCells lastObject] inScrollView:scrollView];
    if (cellCount == 2) {
        return;
    }
    
    //All of the rest of the cells are visible
    for (NSUInteger i = 1; i < cellCount - 1; i++) {
        
    }
    
}

@end















